package com.simple.system.controller;

import com.simple.system.entity.Result;
import com.simple.system.entity.SysUser;
import com.simple.system.service.SysOptLogService;
import com.simple.system.service.SysUserService;
import com.simple.system.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*", maxAge = 3600)
public class SysUserController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysOptLogService operationLogService;

    @GetMapping("/hello")
    public Result<List<SysUser>> hello() {
        List<SysUser> users = userService.getAllUsers();
        return Result.success(users);

    }

    @GetMapping("/hello2")
    public String hello2() {
        return "hello";

    }

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody SysUser user) {
        userService.saveUser(user);
        operationLogService.saveLog(user.getId(), "REGISTER", "User registered: " + user.getUsername());
        return ResponseEntity.ok("User registered successfully");
    }


    @PostMapping("/login")
    public Result<String> login(@RequestBody SysUser user, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String captcha = (String) session.getAttribute("captcha");
        String inputCaptcha = request.getParameter("captcha");
        //验证码判断
        if (captcha == null ||!captcha.equalsIgnoreCase(inputCaptcha)) {
            return Result.fail(403,"验证码错误");
        }
        SysUser existingUser = userService.getUserByUsername(user.getUsername());
        if(existingUser == null){
            return Result.fail(403,"用户不存在");
        }
        if (userService.validatePassword(user.getUsername(), user.getPassword())) {
            String token = JwtUtils.generateToken(existingUser.getId());
            Map<String, String> response = new HashMap<>();
            response.put("token", token);
            operationLogService.saveLog(existingUser.getId(), "LOGIN", "User logged in: " + existingUser.getUsername());
            session.removeAttribute("captcha");
            return Result.success(token);
        } else {
            String key = "password:error:" + user.getUsername();
            int attempts = (int) userService.getRedisUtil().get(key);
            if (attempts >= userService.getMaxAttempts()) {
                operationLogService.saveLog(existingUser.getId(), "LOGIN", "密码错误3次，锁定10分钟: " + existingUser.getUsername());
                return Result.fail(403,"密码错误次数过多，锁定10分钟!");
            }
            operationLogService.saveLog(existingUser.getId(), "LOGIN", "密码错误: " + existingUser.getUsername());
            return Result.fail(403,"密码错误!");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        operationLogService.saveLog(id, "DELETE", "User deleted: " + id);
        return ResponseEntity.ok("User deleted successfully");
    }

    @PutMapping("/{id}/disable")
    public ResponseEntity<String> disableUser(@PathVariable Long id) {
        userService.disableUser(id);
        operationLogService.saveLog(id, "DISABLE", "User disabled: " + id);
        return ResponseEntity.ok("User disabled successfully");
    }
}    